/**
 * axios中间件
 * @param {*} param0
 */

export default function ({ $cookies, $axios, redirect, store }) {
  let isRefreshing = false // 标记是否正在刷新 token
  let requests = [] // 存储待重发请求的数组\

  const source = $axios.CancelToken.source()

  $axios.onRequest((config) => {
    // 获取服务端的token
    console.log('request-url', config.url)
    console.log('tempTokenGetters', store.getters.tempTokenGetters)
    // 每次请求添加请求记录
    config.cancelToken = source.token
    if ($cookies.get('token')) {
      if (process.server && store.getters.tempTokenGetters) {
        config.headers.Authorization = `Bearer ${store.getters.tempTokenGetters}`
        return config
      } else {
        config.headers.Authorization = `Bearer ${$cookies.get('token')}`
      }
    }
    return config
  })

  /**
   * 响应拦截器的方式
   */
  $axios.interceptors.response.use(
    (response) => {
      return response
    },
    async (err) => {
      if (err && err.response) {
        // console.log('status', err.response.data.path)
        // 判断token
        if (err.response.status === 401) {
          const { config } = err
          if (!isRefreshing) {
            isRefreshing = true
            try {
              const result = await $axios.$post('/auth/refreshtoken', {
                refreshToken: $cookies.get('refreshToken')
              })
              const { accessToken, refreshToken } = result
              // 将返回的新cookie保存到客户端，因为如果不是ssr，$cookies.get是从本机拿cookie
              $cookies.set('token', accessToken)
              $cookies.set('refreshToken', refreshToken)
              // 没有修改成功，还是使用的之前的token
              // config.headers.Authorization = `Bearer ${accessToken}`
              store.commit('changeTempToken', accessToken)
              // token 刷新后将数组的方法重新执行
              requests.forEach((cb) => cb())
              // 重新请求完清空
              requests = []
              return $axios(config)
            } catch (error) {
              // TODO:使用axios取消其他请求
              console.log('抱歉，您的登录状态已失效，请重新登录！')
              isRefreshing = false
              requests = []
              source.cancel('抱歉，您的登录状态已失效，请重新登录！')
              // $cookies.remove('token')
              // $cookies.remove('refreshToken')
              return redirect('/login')
              // return Promise.reject(error)
            }
          } else {
            // 返回未执行 resolve 的 Promise
            return new Promise((resolve) => {
              // 用函数形式将 resolve 存入，等待刷新后再执行
              requests.push((token) => {
                resolve($axios(config))
              })
            })
          }
        } else {
          return Promise.reject(err)
        }
      }
      return Promise.reject(err)
    }
  )

  // $axios.onError((error) => {
  //   console.log('请求异常 error = ', error.response.status)
  //   if (error.response.status === 401) {
  //     $cookies.remove('token')
  //     $cookies.remove('refreshToken')
  //     redirect('/login')
  //   }
  //   return Promise.reject(error)
  // })
}
